﻿var gameModule = angular.module('gameModule', ['ui.bootstrap']);

gameModule.controller('newGameController', ['$scope', '$http', '$location',

    function (scope, http, location) {
        scope.newGameData = null;
        scope.newGameOptions = {
            availablePieces: [
                {name: 'X'},
                {name: 'O'}
            ],
            selectedPiece: {name: 'O'},
            availableGameTypes: [
                {name: 'COMPETITION'},
                {name: 'COMPUTER'}
            ],
            selectedBoardDimension: {name: 'COMPUTER'}
        };

        scope.createNewGame = function () {

            var data = scope.newGameData;
            var params = JSON.stringify(data);

            http.post(httpUrl+"/gwtgame/create", params, {
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8'
                }
            }).success(function (data, status, headers, config) {
                if (data.status==200){
                    location.path('/gwtgame/' + scope.newGameData.gameName);
                }
                else{
                    alert(data.result);
                }
            }).error(function (data, status, headers, config) {
                location.path('/player/panel');
            });
        }

    }
]);


gameModule.controller('playerGamesController', ['$scope', '$http', '$location', '$routeParams',
    function (scope, http, location, routeParams) {

        scope.playerGames = [];

        http.get(httpUrl+'/gwtgame/player/list').success(function (data) {
            scope.playerGames = data.result;
        }).error(function (data, status, headers, config) {
            location.path('/player/panel');
        });

        scope.loadGame = function (id) {
            console.log(id);
            location.path('/gwtgame/' + id);
        }

    }]);
//显示游戏
gameModule.controller('gameController', ['$rootScope', '$routeParams', '$scope', '$http','$uibModal',
    function (rootScope, routeParams, scope, http,uibModal) {
       var gameStatus;
       getInitialData();
        function getInitialData() {
           //加载数据
           http.get(httpUrl+'/gwtgame/' + routeParams.id).success(function (data) {
                scope.gameProperties = data;
                gameStatus = scope.gameProperties.gameStatus;
            }).error(function (data, status, headers, config) {
                scope.errorMessage = "Failed do load game properties";
            });
        }
        //提交命令
        scope.syntaxSubmit = function() {
           if (scope.GameSyntax==undefined){
               alert("请检测命令！")
               return;
           }
            scope.GameSyntax.gameName = routeParams.id;
            scope.GameSyntax.userName = scope.gameProperties.listPlayer[scope.gameProperties.playerIndex].userName;
            //加载数据
            //var params = JSON.stringify(data);
            http.post(httpUrl+'/gwtgame/syntax',scope.GameSyntax).success(function (data) {
                if (data.status==200){
                    window.location.reload();
                }
                else
                {
                    alert(data.result);
                }
            }).error(function (data, status, headers, config) {
                scope.errorMessage = "Failed do load game properties";
            });
        }
        //打开窗口
        scope.openClickWindow = function (action,listPlayer) {
            var isAtPos = false;
            if (listPlayer!=null){
                for (var i=0;i<listPlayer.length;i++){
                    if (scope.gameProperties.currentPlayer.color == listPlayer[i].color){
                        isAtPos = true;
                        break;
                    }
                }
            }
            if (!isAtPos){
                alert("不能点击不在的空间的行动格");
                return;
            }
            var  templateUrl;
            if (action.templateHtml!=undefined){
                templateUrl = '/static/templates/gwt/modal/'+action.templateHtml+'.html';
            }
            else
            {
                templateUrl = '/static/templates/gwt/modal/select_disaster.html';
            }
            var modalInstance = uibModal.open({
                animation:true,
                ariaLabelledBy: 'modal-title',
                ariaDescribedBy: 'modal-body',
                templateUrl: templateUrl,  //载入的html文件
                //templateUrl: '/static/templates/gwt/modal/select_card.html',  //载入的html文件
                controller: action.templateControl,  //为载入的文件定义一个控制器
                size: 'lg',  // size ： lg sm 两值
                resolve: {   //resolve是成功创建模态框时，将有效数据传给模态框的控制器，模态框的控制通过注入的形式获取，这里传送了一个item的值；
                    gameProperties: function () {
                        return scope.gameProperties;
                    },
                    action:function () {
                        return action;
                    },
                    GameSyntax:function () {
                        return scope.GameSyntax;
                    }
                }
            });
            modalInstance.result.then(function (selected) {  //配合模态框模块执行完毕，成功关闭后执行的回调函数。selected是模态框传过来的值。
                //alert(selected);
            }, function () {
                //alert(scope.gameProperties);
            },function (){　　　　　　　　　　　　　　　　　　　　　　　　
                //取消关闭后执行。　　　　
                //
            });
        }
    }
]);
//打牌的控制器
gameModule.controller('PlayCardAction',function($uibModalInstance,$scope,gameProperties,action,GameSyntax){  //此控制器只有在模态框成功打开时才会执行。
    $scope.gameProperties = gameProperties;
    $scope.ok = function () {
        //alert(model.gameName);
        var syntax = action.pattern.replace('(\\d*)',$scope.syntax);
        GameSyntax.syntax = syntax;
        $uibModalInstance.close('wang');  //close方法会将参数值回调返回。
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');  //关闭模态框，也会执行回调。
    };
    //选择卡牌
    $scope.selectCard = function (card) {
        //第一张牌
        if ($scope.syntax===undefined){
            $scope.syntax = card.code
        }
        else{
            $scope.syntax += "," + card.code
        }
        //$scope.ok();
        //alert(action.pattern);
        //alert(card.code);
    };
});
//选择工人
gameModule.controller('BuyWorkerAction',function($uibModalInstance,$scope,gameProperties,action,GameSyntax){  //此控制器只有在模态框成功打开时才会执行。
    $scope.gameProperties = gameProperties;
    $scope.ok = function () {
        //alert(model.gameName);

        $uibModalInstance.close('wang');  //close方法会将参数值回调返回。
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');  //关闭模态框，也会执行回调。
    };
    //选择卡牌
    $scope.selectWorker = function (worker) {
        if (worker.gwtSpaceTile==null){
            alert("不能选择空白工人")
            return;
        }
        var syntax = action.pattern.replace('(\\d*)-(\\d*)',worker.row+'-'+worker.column );
        GameSyntax.syntax = syntax;

        $scope.ok();
    };
});

